from flask import Blueprint, render_template, request, jsonify, abort
from flask_login import login_user, logout_user, current_user, AnonymousUserMixin, \
    login_required  # q80：此处引入了当前登录对象 current_user
from Config import db
from models.my_model import Post, Like, Comment, User, R, Reply
from view.user_view import _query_username_by_id

page_post = Blueprint("page_post", __name__)


@page_post.route("/post", methods=['GET'])
def all_post():
    """
    所有帖子详情
    :return: 帖子详情
    """
    # TODO 所有帖子（帖子详情页面json api接口，后续备用）
    return jsonify({'code': "200", "msg": "all_post"})


@page_post.route("/post/<int:post_id>", methods=['GET'])
def detail(post_id: int):
    """
    特定帖子详情
    :param id: 帖子ID
    :return: 帖子详情
    """
    cu = User()
    if current_user.is_anonymous:
        cu.id = 0
        cu.type =1
    else:
        cu = current_user
    pageSize = 5
    page = request.values.get('page')
    try:
        page: int = int(page)
    except Exception as v:
        print(v)
    if not page:
        page = 1
    # all()出来的要用for循环才能获取 如果单个数据直接first即可
    # 获取post_id对应的post文章信息
    post = Post.query.filter(Post.id == post_id).first()
    # 获取文章作者
    user = User.query.filter(User.id == post.user_id).first()
    post.username = user.username
    post.header_url = user.header_url
    # 获取全部评论
    comment_all = Comment.query.filter(Comment.target_post_id == post_id).paginate(page=page, per_page=pageSize)
    # 获取文章评论的回复
    reply_all = Reply.query.filter(Reply.target_post_id == post_id).all()
    for reply in reply_all:
        user = User.query.filter(User.id == reply.user_id).first()
        reply.username = user.username
        reply.header_url = user.header_url
        print(reply.comment_post_id)
    comment_with_username: list = []
    # 获取当前用户对文章的点赞状态
    user_like_post= Like.query.filter(Like.user_id == cu.id, Like.target_post_id==post_id).first()
    if user_like_post:
        post.like = 1
    else:
        post.like = 0
    # 获取评论的点赞数
    # 获取当前用户点赞的评论
    comment_like_id_all = []
    for comment in comment_all:
        like_count = Like.query.filter(Like.target_comment_id == comment.id).count()
        reply_count = Reply.query.filter(Reply.comment_post_id == comment.id).count()
        comment.like_count = like_count
        comment.reply_count = reply_count
        comment_like = Like.query.filter(Like.user_id == cu.id, Like.target_comment_id == comment.id).first()
        comment.like = 0
        if comment_like:
            comment.like = 1
            comment_like_id_all.append(comment_like.target_comment_id)
    # 将评论者id与用户名对应，传入新list
    for comment in comment_all:
        us:User = User.query.filter(User.id == comment.user_id).first()
        comment.username = us.username
        comment.header_url = us.header_url

    return render_template(
        "post_discuss.html",
        post=post,
        current_user = cu,
        comment_all=comment_all,
        replys=reply_all,
        pagination=comment_all
    )


@page_post.route("/post/publish", methods=['POST', 'GET'])
@login_required
def publish():
    """
    发布帖子，
        - GET方法访问返回页面，
        - POST方法接受一个包含{'auth','title','content'}的json对象
    :return: 页面 或者 {'code': "200", "msg": "insert_OK"}
    """
    # 获取当前登录用户
    cu: User = current_user
    if current_user.is_anonymous == True:
        # return jsonify(R(code=400, msg=f"no user logged in").define())
        return render_template("error_with_msg.html", msg="400 - 无登录用户")

    if request.method == "GET":
        return render_template("post_publish.html")
    elif request.method == "POST":
        print("post")
        json_data = request.json
        json_data = eval(str(json_data))

        try:
            user_id: int = current_user.id
        except Exception as e:
            print(e)
            return jsonify(
                R(4002, "user_id format is not acceptable. Length less than 9 and only in INT would be fine.").define())
        if len(str(user_id)) >= 9:
            return jsonify(R(4003, "user_id too long. Length less than 9 would be fine.").define())
        title = json_data['title']
        content = json_data['content']
        # 验证非空
        if not content or content == "" or not title or title == "":
            return abort(406)
        type = 0
        status = 0
        comment_count = 0
        like_count = 0
        new_post: Post = Post(
            user_id=user_id,
            title=title,
            content=content,
            type=type,
            status=status,
            comment_count=comment_count,
            like_count=like_count
        )
        session: db.session = db.session()
        session.add(new_post)
        session.commit()
        session.close()
        return jsonify({'code': "200", "msg": "发布成功，稍后返回首页..."})
    else:
        return jsonify({'code': "400", "msg": "client_error"})


# 删除文章接口
@page_post.route("/post/delete/<int:id>", methods=['POST', 'GET'])
@login_required
def delete(id):
    # 获取当前登录用户
    cu: User = current_user
    if current_user.is_anonymous == True:
        # return jsonify(R(code=400, msg=f"no user logged in").define())
        return render_template("error_with_msg.html", msg="400 - 无登录用户")
    post = Post.query.filter(Post.id == id).first()
    # 评论根据post_id 查询后删除
    comments = Comment.query.filter(Comment.target_post_id == id).all()
    print(post.user_id)
    # 判定是否是创建者 不是则没有删除
    # 管理员id暂定为 1 用同一个接口删除
    if cu.id == post.user_id or cu.type == 99:
        db.session.delete(post)
        for comment in comments:
            db.session.delete(comment)
        db.session.commit()
        return jsonify({'code': "200", "msg": "delete_OK"})
    else:
        return jsonify({'code': "400", "msg": "no_writer_error"})


# 修改文章接口
@page_post.route("/post/alter/<int:id>", methods=['POST', 'GET'])
@login_required
def alter(id):
    # 获取当前登录用户
    cu: User = current_user
    if current_user.is_anonymous == True:
        # return jsonify(R(code=400, msg=f"no user logged in").define())
        return render_template("error_with_msg.html", msg="400 - 无登录用户")
    post = Post.query.filter(Post.id == id).first()
    try:
        if cu.id == post.user_id or cu.type == 99:
            if request.method == "GET":
                return render_template("post_alter.html", post=post)
            elif request.method == "POST":
                # 获取文章信息
                json_data = request.json
                json_data = eval(str(json_data))
                title = json_data['title']
                content = json_data['content']
                post.title = title
                post.content = content
                # 修改post数据
                db.session.merge(post)
                db.session.commit()

                return jsonify({'code': "200", "msg": "alter_OK"})
            else:
                return jsonify({'code': "400", "msg": "client_error"})
        else:
            return jsonify({'code': "400", "msg": "client_error"})
    except Exception as e:
        print(e)
        userMsg: dict = {
            "usernameMsg": None,
            "passwordMsg": None,
            "codeMsg": None
        }
        return render_template(
            "user_login.html",
            userMsg=userMsg
        )


# 加精 置顶
@page_post.route("/post/add", methods=['POST', 'GET'])
@login_required
def add():
    # 获取json数据
    data = request.get_json()
    print(data)
    # 判断是否为管理员
    if current_user.type >1:
        # 获取post修改post数据用于后面修改post置顶属性
        post: Post = Post.query.filter(Post.id == data["postId"]).first()

        if "postType" in data:
            if data["postType"] == '0':
                post.type = 1
            elif data["postType"] == '1':
                post.type = 0
        if "postStatus" in data:
            if data["postStatus"] == '0':
                post.status = 1
            elif data["postStatus"] == '1':
                post.status = 0
        db.session.merge(post)
        db.session.commit()
    return jsonify({'code': "200", "msg": "update_type_OK", "data": "1"})


@page_post.errorhandler(401)
def user_err_401(error):
    return render_template("error_with_msg.html", msg="拒绝访问", detail="您可能尚未登录或是权限不足")
